package com.ainiyar.springweb.util;

import net.sourceforge.pinyin4j.PinyinHelper;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**************************************
 * File Name : ChineseUtil
 * Created with : IntelliJ IDEA.
 * Author : 艾尼亚尔·毛拉吾提
 * QQ : 524155792  WeChat : ainiyar0124
 * Created Time : 2024/2/21  16:53
 * Desc :中文处理类
 ***************************************/

public class ChineseUtil {
    public static String getFirstLetter(String chinese) {
        StringBuilder sb = new StringBuilder();
        Pattern p = Pattern.compile("[\\u4E00-\\u9FA5]");
        Matcher m = p.matcher(chinese);
        while (m.find()) {
            String c = m.group();
            sb.append(convertToPinyin(c));
        }
        return sb.toString();
    }

    public static String getFirstPinyin(String chinese) {
        String first = getFirstLetter(chinese);
        return String.valueOf(first.charAt(0));
    }

    private static String convertToPinyin(String chinese) {
        String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(chinese.charAt(0));
        if (pinyin != null && pinyin.length > 0) {
            return String.valueOf(pinyin[0].charAt(0)).toUpperCase();
        }
        return "";
    }
}

